<?php

namespace App\Models;

use App\Http\Controllers\ScoreRuleController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 志愿者报名
 * Class ArticleTypeModel
 * @package app\common\model
 */
class VolunteerApply extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'volunteer_apply';



    /*关联志愿者岗位*/
    public function conPosition()
    {
        return $this->hasOne(VolunteerPosition::class, 'id', 'position_id');
        // return $this->hasOne(ActivityType::class,'id', 'type_id')->bind('type_name');
    }


    /**
     * 关联服务类型
     */
    public function intention()
    {
        return $this->belongsToMany('App\Models\VolunteerServiceIntention', 'volunteer_apply_intention', 'volunteer_id', 'intention_id');
    }

    /**
     * 关联服务时间
     */
    public function times()
    {
        return $this->belongsToMany('App\Models\VolunteerServiceTime', 'volunteer_apply_time', 'volunteer_id', 'times_id');
    }

    /**
     * 教育程度
     */
    public function getDegree($id = null)
    {
        $data = ['1' => '小学', '初中', '高中', '中专', '大专', '本科', '硕士', '博士', '其他'];
        if ($id) {
            return $data[$id];
        }
        return $data;
    }
    /**
     * 教育程度
     */
    public function getHealth($id = null)
    {
        $data = ['1' => '良好', '较好', '较差'];

        if ($id) {
            return $data[$id];
        }
        return $data;
    }
    /**
     * 性别
     */
    public function getSex($id = null)
    {
        $data = ['1' => '男', '女'];

        if ($id) {
            return $data[$id];
        }
        return $data;
    }


    /**
     * 获取志愿者对应数据个数
     */
    public function getVolunteerNumber($position_id = null, $status = [])
    {
        return $this->where(function ($query) use ($position_id, $status) {
            if ($position_id) {
                $query->where('position_id', $position_id);
            }
            if ($status) {
                $query->whereIn('status', $status);
            }
        })->count();
    }



    /**
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param degree string 教育程度 空表示全部
     * @param intention_id int  服务意向id  多个逗号拼接
     * @param times_id int  服务时间id  多个逗号拼接
     * @param sex int 性别  0 或空 1 男  2 女
     * @param max_age int 最大年龄
     * @param mim_age int 最小年龄
     * @param status tinyint 状态  0 或空 全部 1 通过 2 拒绝 3 待审核
     * @param sort tinyint 排序   1 默认排序  2 服务时长排序
     */
    public function lists($keywords = null, $status = null, $degree = null, $intention_id = null, $times_id = null, $sex = null, $mim_age = null, $max_age = null, $sort = 'id desc', $limit = 10)
    {
        //获取满足条件的志愿者id
        $volunteer_id = $this->getVolunteerId($intention_id, $times_id);

        //   DB::enableQueryLog();
        $res = $this->with(
            ['intention' => function ($query) {
                $query->where('is_del', 1);
            }, 'times' => function ($query) {
                $query->where('is_del', 1);
            }]
        )->from($this->table . ' as v')
            ->join('user_info as u', 'u.id', '=', 'v.user_id')
            ->select('v.*', DB::raw("(YEAR(CURDATE())-YEAR(birth)) as age"), 'u.volunteer_service_time')
            //->join('volunteer_position as p', 'p.id', '=', 'a.position_id')
            ->where(function ($query) use ($keywords) {
                if (!empty($keywords)) {
                    $query->where('v.username', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($status, $degree, $intention_id, $times_id, $volunteer_id, $sex) {
                if ($status) {
                    $query->where('v.status', $status);
                }
                if ($degree) {
                    $query->where('v.degree', $degree);
                }
                if ($intention_id || $times_id) {
                    $query->whereIn('v.id', $volunteer_id);
                }
                if ($sex) {
                    $query->where('v.sex', $sex);
                }
            });

        //having 好像不支持闭包
        if ($mim_age && $max_age) {
            $res = $res->havingBetween('age', [$mim_age, $max_age]);
        } elseif ($mim_age && empty($max_age)) {
            $res = $res->having('age', '>=', $mim_age);
        } elseif (empty($mim_age) && $max_age) {
            $res = $res->having('age', '<=', $max_age);
        }

        $res = $res->where('v.status', '<>', 2) //去掉已撤销的
            ->orderByRaw($sort)
            ->paginate($limit)
            ->toArray();

        //   dump(DB::getQueryLog());die;
        foreach ($res['data'] as $key => $val) {
            //获取服务时长
            // $res['data'][$key]['volunteer_service_time'] = UserInfo::where('id', $val['user_id'])->value('volunteer_service_time');

            $res['data'][$key]['degree_name'] = $val['degree'] ? $this->getDegree($val['degree']) : '';
            $res['data'][$key]['health_name'] = $val['health'] ? $this->getHealth($val['health']) : '';
            $res['data'][$key]['sex_name'] = $val['sex'] ? $this->getSex($val['sex']) : '';
        }
        return $res;
    }


    /**
     * 获取满足条件的志愿者id
     */
    public function getVolunteerId($intention_id, $times_id = null)
    {
        if (empty($intention_id) && empty($times_id)) {
            return [];
        }
        //查询瞒住条件的id
        $data = [];
        $intention_volunteer_id = [];
        $times_volunteer_id = [];
        if ($intention_id) {
            $intentionModel = new VolunteerApplyIntention();
            $intention_volunteer_id = $intentionModel->getVolunteerIdByIntentionId($intention_id);
            $data = $intention_volunteer_id;
        }
        if ($times_id) {
            $timesModel = new VolunteerApplyTime();
            $times_volunteer_id = $timesModel->getVolunteerIdByTimesId($times_id);
            $data = $times_volunteer_id;
            if ($intention_id) {
                $data = array_intersect($intention_volunteer_id, $times_volunteer_id);
            }
        }
        return $data;
    }


    /**
     * 获取志愿者详情
     * @param id int 志愿者id
     * @param $field int 需要的字段
     */
    public function detail($id = null, $user_id = null, $field = [])
    {
        if (empty($id) && empty($user_id)) {
            return [];
        }
        if (empty($field)) {
            $field = '*';
        }
        $res = $this->select($field)->with(
            ['conPosition' => function ($query) {
                $query->select('id', 'name');
            }, 'intention' => function ($query) {
                $query->where('is_del', 1);
            }, 'times' => function ($query) {
                $query->where('is_del', 1);
            }]
        )
            ->where(function ($query) use ($id, $user_id) {
                if ($id) {
                    $query->where('id', $id);
                } else {
                    $query->where('user_id', $user_id);
                }
            })->orderByDesc('id')
            ->first();

        //dump(DB::getQueryLog());
        if ($res) {
            foreach ($res['intention'] as $key => &$val) {
                unset($val['is_del'], $val['change_time'], $val['pivot']);
            }
            foreach ($res['times'] as $key => &$val) {
                unset($val['is_del'], $val['change_time'], $val['pivot']);
            }
        }

        return $res;
    }


    /**
     * 审核通过 和 拒绝
     * @param id int 申请id
     * @param status int 状态  1.已通过 3.已拒绝
     */
    public function agreeAndRefused($id, $status, $reason = null)
    {
        $res = $this->where('id', $id)->first();
        if (!$res) {
            throw new Exception("参数传递错误");
        }

        if ($res->status != 4) {
            throw new Exception("不处于未审核状态");
        }

        $res->status = $status;
        if ($status == 3) {
            $res->reason = $reason;
        }
        $res->manage_id = request()->manage_id;
        $res->save();
        return $res;
    }

    /**
     * 添加或修改用户志愿者信息  （修改后，自动提交到后台审核）
     * @param token int 用户登录信息
     * @param position_id int 岗位名称
     * @param username int 用户姓名
     * @param tel int   联系电话
     * @param sex int  性别
     * @param id_card int  身份证号码
     * @param birth int  生日
     * @param address int  地址
     * @param school int  毕业院校
     * @param major int  学历
     * @param specialty int  个人特长
     * @param nation int  民族
     * @param politics int  政治面貌
     * @param health int  健康状态
     * @param unit int  工作单位
     * @param degree int  教育程度
     * @param intro int  个人简介
     */
    public function change($user_id, $account_id = null, $data = [])
    {
        if (!empty($data['id_card'])) {
            $data['birth'] = get_user_birthday_by_id_card($data['id_card']);
            $data['sex'] = get_user_sex_by_id_card($data['id_card']);
        }
        $res = $this->where('user_id', $user_id)->first();
        if (empty($res)) {
            $res = $this; //过期也需要新增

            if ($account_id) {
                //操作积分
                $scoreRuleObj = new ScoreRuleController();
                $score_status = $scoreRuleObj->checkScoreStatus(19, $user_id, $account_id);
                if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);
                if ($score_status['code'] == 200) {
                    $scoreRuleObj->scoreChange($score_status, $user_id, $account_id, 0); //添加积分消息
                }
            }
        } elseif ($res->status == 1 || $res->status == 4) {
            throw new Exception('请先撤销，在进行修改');
        }
        $volunteerPositionModel = new VolunteerPosition();
        $volunteerApplyParam = $volunteerPositionModel->volunteerApplyParam();

        $res->user_id = $user_id;
        $res->account_id = $account_id;
        // $res->position_id = $data['position_id'];

        for ($i = 1; $i < 16; $i++) {
            $field = $volunteerApplyParam[$i - 1]['field'];
            $res->$field = !empty($data[$volunteerApplyParam[$i - 1]['field']]) ? $data[$volunteerApplyParam[$i - 1]['field']] : null;
        }
        $res->status = 4; //每次修改都重置为审核中
        $res->save();
        return $res->id;
    }
}
